#region Usings

using System;
using System.Collections.Generic;
using System.Reflection;

using Gonte.ObjectModel;
using Gonte.Reflection; 

#endregion

namespace Gonte.Validation
{
    public static class ObjectValidator
    {
        public static bool Validate(Object @object, ref List<ValidationError> errors)
        {
            TypeAccessor typeAccessor = TypeAccessor.GetTypeAccessor(@object.GetType());

            IValidable validable = @object as IValidable;
            if (validable != null)
            {
                validable.Validate(ref errors);
            }
            else // Create the list
            {
                errors = new List<ValidationError>();
            }

            foreach (PropertyInfo propertyInfo in @object.GetType().GetProperties())
            {
                FieldAttribute[] attributes = CustomAttribute.GetCustomAttributes<FieldAttribute>(propertyInfo, true);
                if (attributes != null)
                {
                    foreach (FieldAttribute fieldAttribute in attributes)
                    {
                        FieldValidator validator = fieldAttribute.CreateValidator();
                        if (!validator.Validate(typeAccessor.GetValue(@object, propertyInfo.Name)))
                        {
                            errors.Add(new ValidationError(propertyInfo.Name, validator.Error));
                        }
                    }
                }
            }

            return errors.Count == 0; // The list is empty
        }
    }
}
